requireJS(['constant', 'site', 'handlebars', 'public'], function (Constant, site, Handlebars, Public) {
    Constant.initHandlebars(Handlebars);
    var header;
    var urlHeader = localStorage.getItem('host');
    var publicUrl = 'http://io.worldunion.cn:8620/';
    var proxyHeader = urlHeader + 'manager/shilianProxy.do?url=';
    //var publicUrl = 'http://test.worldunion.cn:8620/';
    var timeStamp;
    var formList;
    var url = {
        selectQueries: "manager/selectQueries.do",
        Diminishing: "manager/Diminishing.do",
        getShiToke: "manager/getShiToken.do",
        getProvinces: publicUrl + "QueryPrice/Provinces",
        getCity: publicUrl + "QueryPrice/Citys/",
        getAreas: publicUrl + "QueryPrice/Areas/",
        getConstruction: publicUrl + "QueryPrice/GetConstruction/",
        getConstructionDetail: publicUrl + "QueryPrice/GetConstrutionViewInfoById/",
        getBuild: publicUrl + "QueryPrice/GetBuild/",
        getHouse: publicUrl + "QueryPrice/GetHouse/",
        getPrice: publicUrl + "QueryPrice/AutoPrice/",
        getPriceModel: publicUrl + "QueryPrice/AutoPriceByModel",
        getTax: publicUrl + "QueryPrice/TaxCalculation",
        print: publicUrl + "QueryPrice/PrintInfo/",
        getInfo: "manager/getInfo.do"
    }


    //实现智能联想
    var searData = {};  //用来存储地址信息

    var Intelligent_association = {
        creSele: function (obj) {
            var autocomplete = $(obj.el).autocomplete({
                hints: obj.data,
                width: obj.width,
                height: obj.height,
                val: obj.val,
                inputClass: obj.inputClass,
                placeholder: obj.placeholder,
                onSubmit: function (text) {
                    obj.backball(text)
                }
            })
            return autocomplete
        },

        initHuArea: function (idxData) {
            var _this = this;
            var huArea = _this.creSele({						//户口所在地
                el: '.huArea',							//页面上的span节点
                data: '',								//需要搜索的所有数据
                width: 158,
                height: 32,
                val: idxData,									//默认input值
                inputClass: 'huInput',					//把动态生成的input class写进去 以免影响插件原有class
                placeholder: '请输入检索城市名称',
                backball: function (text) {				//用户选择后返回的值
                    searData.huArea = text

                    //获取楼盘详细信息
                    $.ajax({
                        url: proxyHeader + encodeURIComponent(url.getConstructionDetail + text),
                        //headers: {'Authorization': header},
                        data: {token: header},
                        crossDomain: true,
                        xhrFields: {
                            withCredentials: true
                        },
                        success: function (data) {
                            data = JSON.parse(data);
                            $.each(JSON.parse(data.content), function (i, e) {
                                $("#district").val(e.RegionName);
                                $("#loopLine").val(e.AreaLine);
                                if (e.AreaId) {
                                    $("#area_list option[value=" + e.AreaId.toString().substr(0, 6) + "]").prop('selected', true);
                                }
                                $("#address").val(e.DoorpLate);
                                $("#alias").val(e.SaleName);
                            })
                        }
                    })

                    //根据楼盘id获取楼宇信息
                    $.ajax({
                        url: proxyHeader + encodeURIComponent(url.getBuild + text),
                        //headers: {'Authorization': header},
                        data: {token: header},
                        crossDomain: true,
                        xhrFields: {
                            withCredentials: true
                        },
                        success: function (data) {
                            data = JSON.parse(data);
                            data.content = JSON.parse(data.content);
                            var source = $("#build_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data.content;
                            var html = template(list)
                            $('#build_list').html(html)

                            if (!data.content.length) {
                                Constant.fn.Message("I", "该楼盘不存在楼宇名，无法估价!");
                            }
                            /*Aliases
                                :
                                ""
                            ID
                                :
                                3667311
                            Name
                                :
                                "1栋"*/

                            var bid = $("#build_list").val() ? $("#build_list").val() : 0;
                            var area = $("#square").val() ? $("#square").val() : 1;

                            $.ajax({
                                url: proxyHeader + encodeURIComponent(url.getHouse + $("#build_list").val()),
                                //headers: {'Authorization': header},
                                data: {token: header},
                                crossDomain: true,
                                xhrFields: {
                                    withCredentials: true
                                },
                                success: function (data) {
                                    data = JSON.parse(data);
                                    var source = $("#house_list_tpl").html();
                                    var template = Handlebars.compile(source);
                                    try {
                                        var list = JSON.parse(data.content);
                                        var html = template(list)
                                        $('#house_list').html(html)

                                        var hid = $("#house_list").val() ? $("#house_list").val() : 0;

                                        timeStamp = new Date().valueOf();
                                        //自动估价
                                        $.ajax({
                                            url: proxyHeader + encodeURIComponent(url.getPrice + text + '/' + bid + '/' + hid + '/' + area + '/' + timeStamp),
                                            /*data: {
                                                ConstructionId: text,
                                                BuildingId: $("#build_list").val(),
                                                HouseId: $("#house_list").val(),
                                                BuildArea: '2',
                                                CaseId: '',
                                                Address: '',
                                                NearRoad: '',
                                                Landspace: '',
                                                PropertyTypeRate: "",
                                                Floor: "",
                                                TotalFloor: "",
                                                HouseType: "",
                                                Forward: "",
                                            },*/
                                            /*headers: {
                                                'Authorization':
                                                header
                                            }
                                            ,*/
                                            data: {token: header},
                                            crossDomain: true,
                                            xhrFields: {
                                                withCredentials: true
                                            },
                                            success: function (data) {
                                                data = JSON.parse(data);
                                                data = JSON.parse(data.content);
                                                if (data.content) {

                                                }
                                                /*var source = $("#build_list_tpl").html();
                                                var template = Handlebars.compile(source);
                                                var list = data
                                                var html = template(list)
                                                $('#build_list').append(html)*/
                                                $('.price').html('￥' + data.UnitPrice)
                                                $('#totalFloor').val(data.TotalFloor);
                                                $('#floor').val(data.FloorNumber);
                                                $('#term_list').val(data.EndDate.substr(0, 4));
                                                if (data.State != '1') {
                                                    Constant.fn.Message('I', data.Note);
                                                }
                                            },
                                        })
                                    }
                                    catch (e) {
                                        Constant.fn.Message('I', '该房产不可估！')

                                    }
                                },
                            })
                        }
                    })
                }
            })
            $('.huInput').bind('keyup keydown', function (e) {		//监听用户敲击键盘时搜索数据
                if (e.which > 32 && e.which < 126) return
                if (/^[\u4e00-\u9fa5]*$/.test($(this).val()) && $(this).val()) {
                    huArea.hints = _this.getCity()
                    //_this.initHuArea();
                    //console.log(_this.getCity())//赋值数据进插件对象huArea
                }
            })
        },

        /*initHomeArea: function (idxData) {
            var _this = this
            var homeArea = _this.creSele({
                el: '.homeArea',							//页面上的span节点
                data: '',								//需要搜索的所有数据
                width: 158,
                height: 32,
                val: idxData,							//默认input值
                inputClass: 'homeInput',					//把动态生成的input class写进去 以免影响插件原有class
                placeholder: '请输入检索城市名称',
                backball: function (text) {				//用户选择后返回的值
                    searData.homeArea = text
                }
            })
            $('.homeInput').bind('keyup keydown', function (e) {		//监听用户敲击键盘时搜索数据
                if (e.which > 32 && e.which < 126) return
                if (/^[\u4e00-\u9fa5]*$/.test($(this).val())) {
                    homeArea.hints = _this.getCity()						//赋值数据进插件对象huArea
                }
            })
        },*/

        /*获取json文件中的城市*/
        getCity: function () {
            var _this = this;
            var city;
            $.ajax({
                type: 'post',
                url: proxyHeader + encodeURIComponent(url.getConstruction + $("#city_list").val() + '/' + encodeURI($(".huInput").val())),
                //headers: {'Authorization': header},
                data: {token: header},
                crossDomain: true,
                xhrFields: {
                    withCredentials: true
                },
                async: false,
                success: function (data) {
                    data = JSON.parse(data);
                    city = JSON.parse(data.content);
                    //_this.getCity();
                    //_this.initHuArea();
                }
            })
            return city
        },

        /*获取完json数据后转成id 传给后台*/
        getSearId: function (data) {
            var id, city = this.getCity()
            $.each(city, function (idx, item) {
                if (item.name == data) {
                    id = item.id.split(',')
                    return
                }
            })
            return id
        }
    }

    //初始化智能搜索
    Intelligent_association.initHuArea()
    //Intelligent_association.initHomeArea()

    site.send({
        url: url.selectQueries,
        data: {
            admin_id: JSON.parse(localStorage.getItem('content')).admin.id
        },
        callback: function (data) {
            data = JSON.parse(data);
            if (data.type == '1') {
                $('.public-bgContent').show();
                $("#count").html(data.content);

                site.send({
                    url: url.getShiToke,
                    callback: function (data) {
                        data = JSON.parse(data)
                        if (data.type == 1) {
                            localStorage.setItem('token', data.content.Token);

                            header = "Basic " + localStorage.getItem('token')
                            $.ajax({
                                url: proxyHeader + encodeURIComponent(url.getProvinces),
                                type: 'post',
                                //headers: {'Authorization': header},
                                data: {token: header},
                                crossDomain: true,
                                xhrFields: {
                                    withCredentials: true
                                },
                                success: function (data) {
                                    data = JSON.parse(data);
                                    var source = $("#province_list_tpl").html();
                                    var template = Handlebars.compile(source);
                                    var list = JSON.parse(data.content);
                                    var html = template(list)
                                    $('#province_list').html(html)

                                    getcity();
                                }
                                ,
                            })
                        }
                    }
                })

            }
            else {
                //$('.public-bgContent').hide();
                $(".notime").show();
                $("#count").html(0)
            }
        }
    })


    function getcity() {
        $.ajax({
            url: proxyHeader + encodeURIComponent(url.getCity + $("#province_list").val()),
            //headers: {'Authorization': header},
            data: {token: header},
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            success: function (data) {
                data = JSON.parse(data);
                var source = $("#city_list_tpl").html();
                var template = Handlebars.compile(source);
                var list = JSON.parse(data.content);
                var html = template(list)
                $('#city_list').html(html)
            },
        })
    }


    $("#province_list").on('change', function () {
        getcity();
    })

    function getAreas() {
        $.ajax({
            url: proxyHeader + encodeURIComponent(url.getAreas + $("#city_list").val()),
            //headers: {'Authorization': header},
            data: {token: header},
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            success: function (data) {
                data = JSON.parse(data);
                var source = $("#area_list_tpl").html();
                var template = Handlebars.compile(source);
                var list = JSON.parse(data.content);
                var html = template(list)
                $('#area_list').html(html)
            },
        })
    }


    $("#city_list").on('change', function () {
        getAreas();
    })


    function getHouse() {
        $.ajax({
            url: proxyHeader + encodeURIComponent(url.getHouse + $("#build_list").val()),
            data: {token: header},
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            //headers: {'Authorization': header},
            success: function (data) {
                data = JSON.parse(data)
                var source = $("#house_list_tpl").html();
                var template = Handlebars.compile(source);
                var list = JSON.parse(data.content);


                var html = template(list)
                $('#house_list').html(html)
            },
        })
    }

    $("#build_list").on('change', function () {
        getHouse();
    })

    $("#calculate").on('click', function () {
        /*if(parseInt($("#count").text()) < 1){
            Constant.fn.Message("I","评估次数已用完")
            return;
        }*/
        site.send({
            url: url.selectQueries,
            data: {
                admin_id: JSON.parse(localStorage.getItem('content')).admin.id
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == '1') {
                    $("#count").html(data.content);
                    var ConstructionId = $('.huInput').data('id')
                    var BuildingId = $("#build_list").val() ? $("#build_list").val() : 0;
                    var HouseId = $("#house_list").val() ? $("#house_list").val() : 0;
                    var BuildArea = $("#square").val();
                    var Floor = $("#floor").val();
                    var TotalFloor = $("#totalFloor").val();

                    if (!ConstructionId) {
                        Constant.fn.Message('I', "请填写楼盘");
                        return;
                    }
                    if (!BuildingId) {
                        Constant.fn.Message('I', "请选择楼宇");
                        return;
                    }
                    if (!HouseId) {
                        Constant.fn.Message('I', "请选择房号");
                        return;
                    }
                    if (!BuildArea) {
                        Constant.fn.Message('I', "请填写建筑面积");
                        return;
                    }
                    if (!Floor) {
                        Constant.fn.Message('I', "请选择所在楼层");
                        return;
                    }
                    if (!TotalFloor) {
                        Constant.fn.Message('I', "请填写总楼层");
                        return;
                    }
                    timeStamp = new Date().valueOf();
                    $.ajax({
                        type: "POST",
                        url: proxyHeader + encodeURIComponent(url.getPriceModel),
                        data: {
                            ConstructionId: ConstructionId,
                            BuildingId: BuildingId,
                            HouseId: HouseId,
                            BuildArea: BuildArea,
                            CaseId: timeStamp,
                            Address: $("#address").val(),
                            NearRoad: $("#NearRoad").val(),
                            Landspace: $("#view").val(),
                            PropertyTypeRate: $("#pro_type").val(),
                            Floor: Floor,
                            TotalFloor: TotalFloor,
                            HouseType: $("#houseType").val(),
                            Forward: $("#forward").val(),
                            method: 'post',
                            token: header
                        },
                        //data: {token: header},
                        crossDomain: true,
                        xhrFields: {
                            withCredentials: true
                        },
                        //headers: {'Authorization': header},
                        success: function (data) {
                            data = JSON.parse(data);
                            if (data.content) {
                                data = JSON.parse(data.content);
                            }
                            if (data.State != '1') {
                                Constant.fn.Message("I", data.Note);
                            }
                            else {
                                site.send({
                                    url: url.Diminishing,
                                    data: {
                                        admin_id: JSON.parse(localStorage.getItem('content')).admin.id,
                                        ConstructionId: ConstructionId,
                                        BuildingId: BuildingId,
                                        HouseId: HouseId,
                                        CaseId: timeStamp
                                    },
                                    callback: function (data) {
                                        data = JSON.parse(data);
                                        if (data.type == '1') {
                                            //$("#count").html(data.content);
                                            site.send({
                                                url: url.selectQueries,
                                                data: {
                                                    admin_id: JSON.parse(localStorage.getItem('content')).admin.id
                                                },
                                                callback: function (data) {
                                                    data = JSON.parse(data);
                                                    if (data.type == '1') {
                                                        $("#count").html(data.content);
                                                    }
                                                    else {
                                                        $("#count").html(0);
                                                    }
                                                }
                                            })
                                        }
                                        else {

                                        }
                                    }
                                })

                                var source = $("#result_list_tpl").html();
                                var template = Handlebars.compile(source);
                                var list = data
                                var html = template(list)
                                $('#result_list').html(html)

                                $('#result').val(data.TotalPrice);
                            }
                        },
                    })
                }
                else {
                    Constant.fn.Message("I", data.msg);
                }
            }
        })

    })

    $("#taxCal").on('click', function () {
        var EvaluationValue = $('#result').val();
        if (!EvaluationValue) {
            Constant.fn.Message('I', '请先进行评估');
            return;
        }
        $.ajax({
            type: "POST",
            //headers: {'Authorization': header},
            url: proxyHeader + encodeURIComponent(url.getTax),
            data: {
                caseId: timeStamp,
                DivisionId: $("#area_list").val(),
                Purpose: $("#pro_type").val(),
                PropertyRight: $("#product_type").val(),
                LoanType: $("#loan_type").val(),
                IsExpire: $("#IsExpire").val(),
                IsOnlyHouse: $("#IsOnlyHouse").val(),
                IsDownTown: $("#IsDownTown").val(),
                BuildArea: $("#square").val(),
                EvaluationValue: EvaluationValue,
                OriginalValue: $("#buyPrice").val(),

                method: 'post',
                token: header
            },
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            success: function (data) {
                data = JSON.parse(data);
                data = JSON.parse(data.content);
                if (data.IsSuccess) {
                    var list = data.ListCalculationDetail;
                    console.log(list.length)
                    $('#tax').val(list[list.length - 2].CalculationValue);
                    $('#mortgage').val(list[list.length - 1].CalculationValue);
                    /*var source = $("#taxDetail_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data
                    var html = template(list.ListCalculationDetail)
                    $('#taxDetail_list').append(html)*/
                    formList = data;
                } else {
                    Constant.fn.Message("F", data.msg);
                }
            }
        })
    })

    $("#buildMess").on('click', function () {
        var id = $('.huInput').data('id');
        if (!id) {
            Constant.fn.Message('I', '请输入楼盘');
            return;
        }
        window.open('OperaManager/houseEvaluate/buildMess.html?id=' + id);
    })

    $("#taxDetail").on('click', function () {

        if (!$("#result").val() || !$("#tax").val()) {
            Constant.fn.Message("I", "请先估价并且计算税费！")
            return;
        }

        //此处动态创建表单，跳转页面传值参数过长
        //创建url
        var url = "OperaManager/houseEvaluate/taxDetail.html";
        //创建要提交的参数
        var type = $("#typeSelect").val();
        var number = $("#noticeNumber").val();
        var status = $("#statusSelect").val();
        //创建form
        var form = $("<form></form>");
        //设置属性
        form.attr("action", url);
        form.attr("method", "post");
        form.attr("target", "_blank");

        //创建input，即参数
        var inputType = $("<input type='text' id='DivisionId' name='list'/>");
        var List = formList.ListCalculationDetail;
        inputType.attr("value", JSON.stringify(List));


        //注入参数到表单
        form.append(inputType);
        //form.append(inputNumber);
        //form.append(inputStatus);
        //form.append(inputPage);
        form.appendTo("body");
        form.hide();
        //提交表单
        form.submit();
    })

    /*function caseDistribution(typeName, typeRatio, typeNum) {
        // 路径配置
        require.config({
            paths: {
                echarts: 'http://echarts.baidu.com/build/dist'
            }
        });

        // 使用
        require(
            [
                'echarts',
                'echarts/chart/bar' // 使用柱状图就加载bar模块，按需加载
            ],
            function (ec) {
                if (!document.getElementById('echar1')) {
                    return;
                }
                // 基于准备好的dom，初始化echarts图表
                var myChart = ec.init(document.getElementById('echar1'));

                var option = {
                    tooltip : {
                        trigger: 'axis'
                    },
                    legend: {
                        data:['邮件营销','联盟广告','视频广告','直接访问','搜索引擎']
                    },
                    toolbox: {
                        show : true,
                        feature : {
                            mark : {show: true},
                            dataView : {show: true, readOnly: false},
                            magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                            restore : {show: true},
                            saveAsImage : {show: true}
                        }
                    },
                    calculable : true,
                    xAxis : [
                        {
                            type : 'category',
                            boundaryGap : false,
                            data : ['2018/06/01','周二','周三','周四','周五','周六','周日']
                        }
                    ],
                    yAxis : [
                        {
                            type : 'value'
                        }
                    ],
                    series : [
                        {
                            name:'邮件营销',
                            type:'line',
                            stack: '总量',
                            data:[120, 132, 101, 134, 90, 230, 210]
                        },
                        {
                            name:'联盟广告',
                            type:'line',
                            stack: '总量',
                            data:[220, 182, 191, 234, 290, 330, 310]
                        },
                        {
                            name:'视频广告',
                            type:'line',
                            stack: '总量',
                            data:[150, 232, 201, 154, 190, 330, 410]
                        },
                        {
                            name:'直接访问',
                            type:'line',
                            stack: '总量',
                            data:[320, 332, 301, 334, 390, 330, 320]
                        },
                        {
                            name:'搜索引擎',
                            type:'line',
                            stack: '总量',
                            data:[820, 932, 901, 934, 1290, 1330, 1320]
                        }
                    ]
                };

                // 为echarts对象加载数据
                myChart.setOption(option);

                window.onresize = myChart.resize;
            }
        );
    }*/

    /*$("#print").on('click',function () {
        $.ajax({
            url:url.print + timeStamp,
            headers: {'Authorization': header},
            dataType:'text',
            success:function(data){
               /!* console.log(data)
                var reader = new FileReader();
                reader.readAsDataURL(data);
                //window.open(file);*!/
                //$("#jump").attr('href',"data:image/jpeg;base64," + data);
               //window.open("data:image/jpeg;base64," + data);
            }
        })
    })*/

    $("#print").on('click', function () {
        if (!$("#result").val() || !$("#tax").val()) {
            Constant.fn.Message("I", "请先分别获得自动估价结果，税费计算结果后再进行打印!")
            return;
        }
        window.open('OperaManager/houseEvaluate/image.html?caseId=' + timeStamp);
    })

})